var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var sd = require('silly-datetime');
app.get('/', function(req, res) {
    res.send('<h1>Welcome FengChou Realtime Server</h1>');
});
var roomInfo = {};
var sockets = [];
//io.origins("www.chat.com:* www.ws.com:*");
io.set('authorization', function(handshakeData, callback) {
	return callback(null, true);
    //console.dir(handshakeData.headers);
    var referer = handshakeData.headers.referer;
    if (referer.indexOf('chat.com') != -1) {
        return callback(null, true); // error first callback style 
    }
    //console.clear();
    console.log('ERROR：拒绝当前域名访问...');
    console.log(handshakeData.headers.referer);
    return callback('ERROR : 我不认识你，你不要再连我了！', false);
});
// socket  这个socket其实就是自己
var room = io.on('connection', function(socket) {
    //log('/room...');
    var config;
    socket.on('to-room', function(_config) {
        config = _config;
        if (!_config.roomid) {
            log('ERROR roomid为空');
            return false;
        }
        // 将用户昵称加入房间名单中
        if (!roomInfo[config.roomid]) {
            roomInfo[config.roomid] = [];
        }
        if (roomInfo[config.roomid].indexOf(config.mid) === -1) {
            roomInfo[config.roomid].push(config.mid);
            socket.join(config.roomid); // 加入房间
        } else {
            socket.emit('roomstatus', { code: 4, content: '已在当前房间' });
            return false;
        }
        sockets[config.mid] = socket;
        // 通知房间内人员

        socket.broadcast.to(config.roomid).emit('roomsys', { type: 'sys', action: 'joinroom', data: _config, timer: Date.now() });
        room.to(config.roomid).emit('roommember', roomInfo[config.roomid]);
        log(config.nickname + '加入了' + config.roomid);
        log(config.roomid + '房间人数' + roomInfo[config.roomid].length);
    });

    socket.on('room-msg', function(_data) {
        // 验证如果用户不在房间内则不给发送
        // 从房间名单中移除
        if (!config) {
            log('ERROR config 为空');
            return false;
        }
        if (!roomInfo[config.roomid]) {
            socket.emit('roomstatus', { code: 2, content: '没有此房间' });
            return false;
        }
        if (roomInfo[config.roomid].indexOf(config.mid) === -1) {
            socket.emit('roomstatus', { code: 3, content: '没有加入房间，不能发送消息' });
            return false;
        }
        _data.timer = Date.now();
        if (_data['to']) {
            var target = sockets[_data['to']['mid']];
            if (target) {
                target.emit('roommsg', _data);
                socket.emit('roomstatus', { code: 0, type: 'msg_private' });
            } else {
                //log(_data['to']['config.mid'] + "不在线...");
                socket.emit('roomstatus', { code: 1, content: _data['to']['config.mid'] + "不在线..." });
            }
        } else {
            socket.broadcast.to(config.roomid).emit('roommsg', _data);
            socket.emit('roomstatus', { code: 0, type: 'msg_public' });
            //包括自己在内
            //room.in(config.roomid).emit('roommsg', _data);
        }
        if (_data.type == 'img') { _data.img = _data.img ? 'data:image/jpg;base64数据流' : '无效数据'; }
        log(config.nickname + ' 说: ', _data);
    });

    socket.on('room-sys', function(_data) {
        _data.timer = Date.now();
        room.in(config.roomid).emit('roomsys', _data);
        log('room-sys: ', _data);
    });

    socket.on('all-sys', function(_data) {
        _data.timer = Date.now();
        room.emit('allsys', _data);
        log('all-sys: ', _data);
    });

    socket.on('leave', function() {
        log(config.nickname + ' leaveing');
        socket.emit('disconnect');
    });

    socket.on('disconnect', function() {
        // 从房间名单中移除
        if (!config) {
            log('ERROR config 为空');
            return false;
        }
        if (!roomInfo[config.roomid]) {
            log(' -> 房间已无人...');
            return false;
        }
        log(config.nickname + ' disconnecting');
        var index = roomInfo[config.roomid].indexOf(config.mid);
        if (index !== -1) {
            roomInfo[config.roomid].splice(index, 1);
        }
        // 退出房间
        socket.leave(config.roomid, function(err) {
            if (err) {
                log(err);
                return;
            }
            log(config.mid + ' -> 成功退出房间...');
        });
        //socket.broadcast.to(config.roomid).emit('roomsys', { type: 'sys', content: user + '退出了房间' });
        socket.broadcast.to(config.roomid).emit('roomsys', { type: 'sys', action: 'outroom', data: config, timer: Date.now() });
        room.to(config.roomid).emit('roommember', roomInfo[config.roomid]);
        log(config.nickname + '离开了' + config.roomid);
        log(config.roomid + '房间人数' + roomInfo[config.roomid].length);
    });
});

function log(_string, _data) {
    //var t = new Date(new Date().getTime() + 28800000);
    var time = sd.format(new Date(), 'YYYY-MM-DD HH:mm:ss');
    //console.log(time);
    console.log(time + '  ' + _string, _data === undefined ? '' : _data);
}

http.listen(3030, function() {
    var time = sd.format(new Date(), 'YYYY-MM-DD HH:mm:ss');
    console.log('-----------' + time + '--------------');
    console.log('server listening on port :3030');
    console.info('websocket runing...');
    console.log('======================运行日志=====================');
});